<template>
	<view class="run-chat flex-column-start-center" :style="{ 'background-image': `url(${bgUrl})` }">
		<view class="top-avatar flex-row-start-center" @click="handleHeadClick"
			:style="{ 'margin-top': (menuButtonInfo.top + (menuButtonInfo.height - 48) / 2) + 'rpx' }">
			<image class="avatar-box" src="https://cdn.osisx.com/runse/images/default-avatar.png" mode="aspectFill">
			</image>
		</view>
		<view class="center-messages" :style="{ 'margin-top': (36 + (menuButtonInfo.height - 48) / 2) + 'rpx' }">
			<scroll-view scroll-y :enhanced="true" :show-scrollbar="false" class="custom-scroll-view"
				:scroll-into-view="scrollToId" :scroll-with-animation="true">
				<view class="message-list">
					<view class="message-item flex-row-start-start"
						:class="{ 'user-message': item.userId == userInfo.userId, 'firend-message': item.userId != userInfo.userId }"
						v-for="(item, index) in messageList" :id="'item-' + index" :key="index">
						<view class="message-item-content" :style="{ 'max-width': (menuButtonInfo.left - 44) + 'rpx' }">
							{{ item.content }}
						</view>
					</view>
				</view>
			</scroll-view>


		</view>
		<view class="bottom-btn-box" :style="{ height: bottomBtnHeight }">
			<view class="btn-content flex-row-center-center"
				:class="{ 'hide-bottom-btn': inputValue || isFocused || isRunSeLoading }" @click="handleToSayClick">
				说点什么~
			</view>
		</view>

		<!-- 输入框 -->
		<view class="input-box">
			<view class="input-component flex-column-start-center" :style="{ bottom: keyBottom }"
				:class="{ 'input-keep-show': inputValue && keyBoardHeight === 0 }">
				<view class="top-magic">
					<view class="magic-btn flex-row-start-center" @click="handleRunSeBtnClick">
						<image class="magic-btn-content" src="https://cdn.osisx.com/runse/images/magic-icon.png"
							mode="aspectFill"></image>
						<view class="magic-btn-text">灵动表达</view>
					</view>
					<view class="input-area flex-row-start-end">
						<view class="input-area-content flex-row-start-center">
							<view class="magic-loading" v-if="isRunSeLoading&&!magicText">灵动表达中~</view>
							<!-- 	<textarea v-model="magicValue" class="area-component" :auto-height="true"
								:adjust-position="false" :show-confirm-bar="false" disabled="true" /> -->
							<view class="area-component" @click="handleMagicTextClick">
								{{magicText}}
							</view>
						</view>
						<view class="input-send-box" @click="handleSendMagicMessage">
							<image class="input-send-btn" src="https://cdn.osisx.com/runse/images/ai-send-btn.png"
								mode="aspectFill">
							</image>
						</view>
					</view>

				</view>
				<view class="input-area flex-row-start-end">
					<view class="input-area-content flex-row-start-center">
						<textarea v-model="inputValue" class="area-component" :focus="isFocused" :auto-height="true"
							:adjust-position="false" :show-confirm-bar="false" @focus="onFocus" @blur="onBlur"
							@keyboardheightchange="handleBordHeightChange" @input="handleInput" />
					</view>
					<view class="input-send-box" @click="handleSendMessage">
						<image class="input-send-btn" src="https://cdn.osisx.com/runse/images/user-send-btn.png"
							mode="aspectFill">
						</image>
					</view>
				</view>
			</view>
		</view>




	</view>
</template>

<script>
	import {
		mapGetters,
		mapState,
		mapMutations
	} from 'vuex';
	import {
		getUserFriends,
		getRoomMessage
	} from "@/api/mbti.js"
	import socketService from './socket.js';
	import {
		login
	} from "@/utils/mbti-login.js"
	export default {
		data() {
			return {
				// socket: null,
				bgUrl: "https://cdn.osisx.com/runse/images/bg.png",
				magicValue: "",
				testValue: "",
				inputValue: "",
				keyBoardHeight: 0,
				isFocused: false,
				keyBottom: '-400rpx',
				inputKeepShow: false,
				bottomBtnHeight: "166rpx",
				scrollToId: "",
				userFriend: null,
				isRunSeLoading: false,
				timer: null

				// messageList: [{
				// 		_id: '0',
				// 		content: "宝宝在干嘛",
				// 		userId: "b1c3c995-a593-4e9c-86ec-4ba8110c755f",
				// 		firendId: "9ac65159-a716-4637-9a38-342a925e16ca"
				// 	},
				// 	{
				// 		_id: '1',
				// 		content: "在想你呀",
				// 		userId: "9ac65159-a716-4637-9a38-342a925e16ca",
				// 		firendId: "b1c3c995-a593-4e9c-86ec-4ba8110c755f"
				// 	},

				// ]

			};
		},
		onShow() {
			// this.handleGetMessageList()
			this.handleGetUserFirends()

		},
		created() {},
		computed: {
			...mapState(['screenWidth', 'userInfo', 'messageList']),
			...mapGetters(['menuButtonInfo', 'systemInfo', 'magicText']),
		},
		watch: {
			messageList: {
				handler(newVal, oldVal) {
					this.scrollToBottom()
				}
			},
			magicText: {
				handler(newVal, oldVal) {
					if (newVal) {
						this.isRunSeLoading = false
					}
				}
			}
		},
		methods: {
			...mapMutations(['updateMessageList', 'updateMagicText']),
			handleMagicTextClick() {
				if (this.magicText) {
					this.inputValue = this.magicText
				}
			},
			handleInput(e) {
				const value = e.detail?.value || e.target?.value || "";
				if (this.timer) {
					clearTimeout(this.timer);
					this.timer = null
				}
				if (!value || value.trim() === '') {
					this.isRunSeLoading = false
					return;
				} else {
					this.updateMagicText("")
					this.isRunSeLoading = true
				}
				this.timer = setTimeout(() => {
					console.log("执行一次")
					this.handleToMagicValue()
				}, 1800);
			},
			handleRunSeBtnClick() {
				if (this.isRunSeLoading) {
					return
				}
				this.handleToMagicValue()
			},
			handleToMagicValue() {
				console.log('正在执行')
				if (this.systemInfo.platform == "devtools") {
					this.keyBottom = "0rpx"
					this.bottomBtnHeight = "282rpx"
				}
				this.updateMagicText("")
				this.isRunSeLoading = true
				let time = new Date().getTime()
				socketService.emit("polishMessage", {
					originalMessage: this.inputValue,
					senderId: this.userInfo.userId,
					receiverId: this.userFriend.userId,
					chatType: 'friend',
					requestId: this.userInfo.userId + this.userFriend.userId + time
				})
			},
			handleSendMagicMessage() {
				if (!this.magicText) {
					return
				}
				// this.isFocused = false
				socketService.emit('friendMessage', {
					userId: this.userInfo.userId,
					friendId: this.userFriend.userId,
					content: this.magicText,
					width: 0,
					height: 0,
					messageType: "text",
				})
				this.updateMagicText("")
				this.inputValue = ""
				this.keyBottom = "-400rpx"
				this.bottomBtnHeight = "166rpx"


			},
			handleSendMessage() {
				if (!this.inputValue) {
					return
				}
				let inputValue = this.inputValue
				this.inputValue = ""
				this.updateMagicText("")
				this.isFocused = false
				this.isRunSeLoading = false

				socketService.emit('friendMessage', {
					userId: this.userInfo.userId,
					friendId: this.userFriend.userId,
					content: inputValue,
					width: 0,
					height: 0,
					messageType: "text",
				})

				if (this.timer) {
					clearTimeout(this.timer)
					this.timer = null
				}
			},
			async handleGetUserFirends() {
				// uni.showLoading()
				let res = await login()
				if (!res.hasRegister) {
					uni.navigateTo({
						url: "/pages/runChat/collectInformation"
					})
					return
				}

				// 初始化的时候只进入自己的房间
				if (!socketService.isConnected) {
					let that = this
					socketService.connect(this.userInfo.userId)
					socketService.on("polishMessageResponse", res => {
						console.log("润色后的信息是", res)
						this.isRunSeLoading = false
						let str = res.data?.polishedMessage ? res.data?.polishedMessage : ""
						this.updateMagicText(str)
					})

					socketService.on('linkSuccess', res => {
						console.log("连接成功")
						// uni.showToast({
						// 	title: "连接成功",
						// 	icon: "none"
						// })

						if (this.userFriend && this.userInfo) {
							socketService.emit("joinFirendRoom", {
								userId: this.userInfo.userId,
								friendId: this.userFriend.userId
							})
						}

					})
				}

				getUserFriends({
					userId: this.userInfo.userId
				}).then(res => {
					try {
						if (res.data.friends.length) {
							this.userFriend = res.data.friends[0]
						}
					} catch (error) {
						//TODO handle the exception
					}
					// 没有朋友
					if (!this.userFriend) {
						uni.navigateTo({
							url: "/pages/runChat/invitePage"
						})
					} else {
						// 有朋友
						socketService.emit("joinFirendRoom", {
							userId: this.userInfo.userId,
							friendId: this.userFriend.userId
						})
						// 获取聊天记录
						this.handleGetMessageList()
					}


				})
			},
			initSocket() {},
			handleGetMessageList() {
				// uni.showLoading()
				// 获取所有消息
				getRoomMessage({
					userId: this.userInfo.userId,
					friendId: this.userFriend.userId
				}).then(res => {
					// uni.hideLoading()
					this.updateMessageList(res.data)
					this.scrollToBottom()
				}).catch(err => {
					// uni.hideLoading()
				})
			},
			handleHeadClick() {
				uni.navigateTo({
					url: "/pages/runChat/collectInformation"
				})
			},
			handleToSayClick() {
				// uni.navigateTo({
				// 	url: "/pages/runChat/invitePage"
				// })
				// return
				this.isFocused = true;
				if (this.systemInfo.platform == "devtools") {
					this.keyBottom = "0rpx"
					this.bottomBtnHeight = "282rpx"
				}
			},
			pxToRpx(px, screenWidth) {
				const designWidth = 750; // 设计稿宽度
				const rpx = (designWidth / screenWidth) * px; // 根据屏幕宽度计算 rpx
				return rpx;
			},
			onFocus() {
				this.isFocused = true
				this.scrollToBottom()
			},
			onBlur() {
				this.isFocused = false
				this.$nextTick(() => {
					if (this.inputValue || this.isRunSeLoading || this.magicText) {
						if (!this.inputValue && this.magicText) {
							this.keyBottom = "-400rpx"
							this.bottomBtnHeight = '166rpx'
						} else {
							this.keyBottom = "0rpx"
							if (this.systemInfo.platform == "devtools") {
								this.bottomBtnHeight = '282rpx'
							}
						}
					} else {
						this.keyBottom = "-400rpx"
						this.bottomBtnHeight = '166rpx'
					}
				})



			},
			handleBordHeightChange(e) {
				this.$nextTick(() => {
					let {
						height
					} = e.detail
					this.keyBoardHeight = height
					if (height > 100) {
						this.keyBottom = this.pxToRpx(height, this.screenWidth) + 'rpx'
						this.bottomBtnHeight = (282 + this.pxToRpx(height, this.screenWidth)) + 'rpx'
					} else {
						if (this.inputValue) {
							// this.bottomBtnHeight = "322rpx"
							this.bottomBtnHeight = "282rpx"
						} else {
							this.bottomBtnHeight = "166rpx"
						}
					}
					this.scrollToBottom()
				})


			},
			scrollToBottom() {
				console.log("滚动")
				setTimeout(() => {
					this.scrollToId = ''; // 设置为一个空值
					this.$nextTick(() => {
						this.scrollToId = 'item-' + String(this.messageList.length - 1)
					});
				}, 300)
			}
		}
	}
</script>

<style lang="scss">
	.run-chat {
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		background-repeat: no-repeat;
		background-size: cover;
		background-position: center center;
		overflow: hidden;

		.top-avatar {
			width: 100%;
			height: 48rpx;
			padding: 0rpx 42rpx;

			.avatar-box {
				width: 48rpx;
				height: 48rpx;
				border-radius: 50%;
			}
		}

		.center-messages {
			width: 100%;
			flex: 1;
			padding: 0rpx 44rpx;
			overflow: hidden;

			.custom-scroll-view {
				width: 100%;
				height: 100%;
			}

			.message-list {
				width: 100%;

				.message-item {
					width: 100%;
					margin-bottom: 44rpx;

					.message-item-content {
						display: inline-block;
						padding: 28rpx 30rpx;

						font-family: "MiSans-Regular";
						font-weight: 400;
						font-size: 30rpx;
						line-height: 40rpx;
					}
				}

				.firend-message {
					justify-content: flex-start;

					.message-item-content {
						color: #4C4141;
						text-align: left;
						background: #FFFFFF;
						border-radius: 4rpx 24rpx 24rpx 24rpx;
					}

				}

				.user-message {
					justify-content: flex-end;

					.message-item-content {
						color: #272F5F;
						text-align: left;
						background: #D2C7FC;
						border-radius: 24rpx 4rpx 24rpx 24rpx;
					}

				}

			}
		}

		.bottom-btn-box {
			position: relative;
			width: 100%;
			height: 166rpx;
			padding: 0rpx 118rpx;
			margin-top: 44rpx; //暂时 防止不好看
			z-index: 2;
			transition: height 0.1s ease-in-out;

			.btn-content {
				flex: 1;
				height: 86rpx;
				border-radius: 46rpx;
				font-family: "MiSans-Normal";
				font-weight: 400;
				font-size: 34rpx;
				line-height: 86rpx;
				background: linear-gradient(135deg, #FE85EB 0%, #616CFF 100%);
				color: #FFFFFF;
			}
		}

		.input-box {
			position: absolute;
			left: 0rpx;
			top: 0rpx;
			z-index: 99999;
			width: 100vw;
			height: 100vh;
			box-sizing: border-box;
			pointer-events: none;
			overflow: hidden;
		}

		.input-component {
			position: absolute;
			left: 0rpx;
			bottom: -400rpx;
			width: 100%;
			gap: 28rpx;
			padding: 0rpx 30rpx;
			transition: all 0.1s ease-in-out;
			z-index: 999;
			padding-bottom: 28rpx;
			pointer-events: fill;

			.top-magic {
				width: 100%;
				padding: 22rpx 18rpx;
				background: #FFFFFF;
				border-radius: 12rpx;
				min-height: 142rpx;
				padding-bottom: 14rpx;

				.magic-btn {
					width: 100%;
					height: 32rpx;
					margin-bottom: 18rpx;

					.magic-btn-content {
						width: 32rpx;
						height: 32rpx;
						margin-right: 12rpx;
					}

					.magic-btn-text {
						display: inline-block;
						height: 28rpx;
						font-family: "MiSans-Light";
						font-weight: 300;
						font-size: 22rpx;
						color: #979797;
						line-height: 28rpx;
					}

				}

				.input-area {
					padding: 0rpx;

					.input-area-content {
						position: relative;

						.magic-loading {
							position: absolute;
							left: 0rpx;
							bottom: 0rpx;
							width: 100%;
							height: 56rpx;
							min-height: 56rpx;
							font-family: "MiSans-Regular";
							font-weight: 400;
							font-size: 30rpx;
							// color: #272F5F;
							color: #979797;
							line-height: 56rpx;
							z-index: 9;
							pointer-events: none;

						}


						.area-component {
							font-family: "MiSans-Regular";
							font-weight: 400;
						}
					}
				}
			}

			.input-area {
				width: 100%;
				padding: 14rpx 18rpx;
				background: rgba(255, 255, 255, 0.8);
				border-radius: 12rpx;
				overflow: hidden;
				gap: 12rpx;
			}

			.input-area-content {
				flex: 1;
				min-height: 56rpx;
				overflow: hidden;

				.area-component {
					flex: 1;
					min-height: 40rpx;
					font-family: "MiSans-Light";
					font-weight: 300;
					font-size: 30rpx;
					color: #272F5F;
					line-height: 40rpx;
				}

			}

			.input-send-box {
				width: 56rpx;
				height: 56rpx;

				.input-send-btn {
					width: 56rpx;
					height: 56rpx;
				}
			}
		}

		.input-show {
			// z-index: 9;
			// opacity: 1;
			// transform: translateY(0);
		}

		.input-keep-show {
			// padding-bottom: 68rpx;
		}

		.hide-bottom-btn {
			// display: none;
			opacity: 0;
		}
	}
</style>